<template>
  <a-tree-select
    :value="modelValue"
    :replaceFields="replaceFields"
    :filterTreeNode="filterTreeNode"
    show-search
    style="width: 100%"
    :multiple="multiple"
    :maxTagCount="1"
    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
    :tree-data="treeData"
    :placeholder="placeholder"
    tree-default-expand-all
    :getPopupContainer="(node) => node.parentNode"
    @change="handleChange"
  ></a-tree-select>
</template>

<script>
import { getAction } from '@/api/manage'
export default {
  props: {
    value: {
      type: [String, Number],
    },
    multiple: {
      type: Boolean,
      default: false, // 是否支持多选
    },
    authAll: {
      type: Boolean,
      default: false, // 是否有权限查看全部经营类目，默认只能查看自己的
    },
    // 内容提示
    placeholder: {
      type: String,
      default: '请选择经营类目',
    },
  },
  model: {
    prop: 'value',
    event: 'change',
  },
  data() {
    return {
      treeData: [],
      modelValue: '',
      replaceFields: {
        key: 'id',
        title: 'name',
        children: 'children',
        value: 'id',
      },
      url: {
        list_: '/hzkj-product/product/productLibrary/category/rootList',
        childList: '/hzkj-product/product/productLibrary/category/childList',
        queryMyCategory: '/hzkj-product/product/productLibrary/category/queryMyCategory',
      },
      ipagination: {
        current: 1,
        pageSize: 20,
      },
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        if (this.multiple) {
          this.modelValue = val ? String(val).split(',') : []
        } else {
          this.modelValue = val ? val : undefined //处理值为空字符串时placeholder不显示问题
        }
      },
    },
  },
  methods: {
    filterTreeNode(inputValue, treeNode) {
      try {
        return (
          treeNode &&
          treeNode.data &&
          treeNode.data.props &&
          treeNode.data.props.title &&
          treeNode.data.props.title.indexOf(inputValue) > -1
        )
      } catch (e) {}
    },
    loadData_(arg, categoryId, flag = false) {
      return new Promise(async (resolve, reject) => {
        this.treeData = []
        if (!this.authAll) {
          // 获取自己权限下的数据
          let treeData = await this.queryMyCategory(categoryId, flag)
          resolve(treeData)
          return
        }
        //加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1
        }
        var params = {
          pageNo: this.ipagination.current,
          pageSize: this.ipagination.pageSize,
          ...this.queryParam,
        }
        getAction(this.url.list_, params)
          .then(async (res) => {
            if (res.success) {
              let treeData = (res.result && res.result.records) || []
              await Promise.all(
                treeData.map(async (item) => {
                  // return无效,直接使用赋值
                  if (item.hasChild && item.hasChild === '1') {
                    item.children = await this.getchildList(item, flag)
                  }
                })
              )
              // 处理assignerList
              this.treeData = treeData
              resolve(this.treeData)
            } else {
              this.$message.warning(res.message)
            }
          })
          .finally(() => {
            this.loading = false
          })
      })
    },
    handleTreeData(treeData, flag) {
      return (treeData = treeData.map((item) => {
        return {
          ...item,
          children: item.children && item.children.length ? this.handleTreeData(item.children, flag) : null,
          disabled: flag ? true : false,
        }
      }))
    },
    handleTreeData_(treeData, categoryId, flag) {
      return (treeData = treeData.map((item) => {
        let curItem = {
          ...item,
          children:
            item.children && item.children.length ? this.handleTreeData_(item.children, categoryId, flag) : null,
          disabled: flag || (item.isDeleted && item.id != categoryId) ? true : false,
        }
        if (!(curItem.children && curItem.children.length)) {
          delete curItem.children
        }
        return curItem
      }))
    },
    queryMyCategory(categoryId, flag) {
      return new Promise((resolve, reject) => {
        getAction(this.url.queryMyCategory, { includeIds: categoryId }).then((res) => {
          if (res.success) {
            let treeData = res.result || []
            this.treeData = this.handleTreeData_(treeData, categoryId, flag)
            resolve(this.treeData)
          } else {
            this.$message.warning(res.message)
          }
        })
      })
    },
    getchildList(item, flag) {
      return new Promise((resolove, reject) => {
        getAction(this.url.childList, { pid: item.id }).then(async (res) => {
          if (res.success) {
            let records = (res.result && res.result.records) || []
            await Promise.all(
              records.map(async (item) => {
                // return无效,直接使用赋值
                if (item.hasChild && item.hasChild === '1') {
                  item.children = await this.getchildList(item, flag)
                }
                item.disabled = flag ? true : false
              })
            )
            resolove(records)
          } else {
            this.$message.warning(res.message)
          }
        })
      })
    },
    handleChange(selectedValue) {
      let oldValue = this.modelValue
      this.modelValue = selectedValue
      if (this.multiple) {
        if (selectedValue.length === 0) {
          this.$emit('change', undefined, oldValue)
        } else {
          this.$emit('change', selectedValue.length > 1 ? selectedValue.join(',') : selectedValue[0], oldValue)
        }
      } else {
        this.$emit('change', selectedValue, oldValue)
      }
    },
  },
  created() {
    // 初始化数据
    this.loadData_('', this.value)
  },
}
</script>
